<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------

namespace app\model;

use think\Model;

/**
 * @title: 用户模型
 */
class Member extends Model {

	protected $pk = 'uid';

	protected $createTime = 'reg_time';
	protected $updateTime = 'last_login_time';

	protected $insert = ['reg_ip'];

	protected $type = [
		'uid'      => 'integer',
		'reg_time' => 'integer',
	];

	public $loginVisible = array('uid', 'username', 'nickname', 'access_token'); //用户登录成功返回的字段

	protected function setPasswordAttr($value) {
		$salt = rand_string(6);
		$this->set('salt', $salt);
		return md5($value . $salt);
	}

	protected function setRegIpAttr($value) {
		return get_client_ip(1);
	}

	protected function getAccessTokenAttr($value, $data) {
		return authcode($data['uid'] . '|' . $data['username'] . '|' . $data['password'], 'ENCODE');
	}

	/**
	 * @title  用户登录
	 * param  username:用户名、手机号码、邮箱 password:密码、手机验证码、开源类型 type:登录类型（账号密码登录、手机号码+验证码登录、开源账号登录）
	 */
	public function login($username, $password, $type = 1) {
		$map  = array();
		if (preg_match("/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/", $username)) {
			$type = 2;
		} elseif (preg_match("/^1[34578]{1}\d{9}$/", $username)) {
			$type = 3;
		}
		switch ($type) {
		case 1:
			$map['username'] = $username;
			break;
		case 2:
			$map['email'] = $username;
			break;
		case 3:
			$map['mobile'] = $username;
			break;
		default:
			return false; //参数错误
		}
		if (!$username) {
			return false;
		}

		$user = $this->where($map)->find();
		if (isset($user['uid']) && $user['uid'] && $user['status']) {
			/* 验证用户密码 */
			if (md5($password . $user['salt']) === $user['password']) {
				/* 更新登录信息 */
				(new MemberLog())->record($user);
				return $user->append(array('access_token'))->visible($this->loginVisible)->toArray(); //登录成功，返回用户信息
			} else {
				$this->error = "密码错误";
				return false; //密码错误
			}
		} else {
			$this->error = "用户不存在或被禁用";
			return false;
		}
	}

	/**
	 * @title: 注册
	 */
	public function register($data) {
		$result = self::create($data);
		if (false !== $result) {
			$user = $this->where('uid', $result->uid)->find();
		} else {
			$this->error = "注册失败！";
			return false;
		}
		/* 更新登录信息 */
		(new MemberLog())->record($user);
		return $user->append(array('access_token'))->visible($this->loginVisible)->toArray(); //登录成功，返回用户信息
	}

	/**
	 * @title: 获取用户列表
	 */
	public function getUserList() {

	}

	/**
	 * @title: 获取用户信息
	 */
	public function getInfo($uid) {

	}

	public function socialite() {
		return $this->hasMany('MemberSocialite', 'uid', 'uid');
	}
}